package com.ccg.securityConfig;

import com.ccg.entity.Permission;
import com.ccg.entity.User;
import com.ccg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;

//security自定义验证登陆用户时的数据来源，从数据库获取
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    UserService userService;
    /**
     * 根据用户名获取用户信息
     *
     * @param s 用户名
     * @return User 返回一个用户信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //BCryptPasswordEncoder bcpe = new BCryptPasswordEncoder();
        User user = userService.findUserByUsername(s);
        if(user!=null) {
            List<Permission> list = userService.findPermsByUsername(s);
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Permission p : list) {
                GrantedAuthority authority = new SimpleGrantedAuthority(p.getPermTag());
                authorities.add(authority);
            }
            //将权限集合放进user
            user.setAuthorities(authorities);
            System.out.println("当前用户是： " + user.getUsername());
        }
        return user;
    }
}
